package com.red.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.red.constant.MessageConstant;
import com.red.dto.UserDto;
import com.red.dto.UserLoginDTO;
import com.red.entity.Users;
import com.red.exception.UserNotLoginException;
import com.red.mapper.UserMapper;
import com.red.properties.WeChatProperties;
import com.red.service.UserService;
import com.red.utils.HttpClientUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;

/**
 * @author 刘英豪
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, Users> implements UserService {

    private static final String WX_LOGIN_URL = "https://api.weixin.qq.com/sns/jscode2session";

    @Autowired
    private WeChatProperties weChatProperties;
    @Autowired
    private UserMapper userMapper;

    /**
     * 微信登录
     *
     * @param userLoginDTO
     * @return
     */
    public Users wxLogin(UserLoginDTO userLoginDTO) {

        //调用微信接口获取openID

        HashMap<String, String> map = new HashMap<>();
        map.put("appid",weChatProperties.getAppid());
        map.put("secret",weChatProperties.getSecret());
        map.put("js_code",userLoginDTO.getCode());
        map.put("grant_type","authorization_code");

        String json = HttpClientUtil.doGet(WX_LOGIN_URL, map);
        JSONObject jsonObject = JSON.parseObject(json);
        String openid = jsonObject.getString("openid");
        //判断是否获取到openid
        if (openid==null){
            throw new UserNotLoginException(MessageConstant.LOGIN_FAILED);
        }

        //判断是否是新用户
        QueryWrapper<Users> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.eq("openid",openid);
        Users users = userMapper.selectOne(userQueryWrapper);

        if (users ==null){
            users = new Users();
            users.setOpenid(openid) ;
            users.setCreatedAt(LocalDateTime.now());
            users.setNickname("tom");
            userMapper.insert(users);
        }
        return userMapper.selectOne(userQueryWrapper);
    }

    /**
     * 用户信息修改
     * @param userDto
     */
    public void updateUser(UserDto userDto) {
        Users users = new Users();
        BeanUtils.copyProperties(userDto,userDto);
        users.setUpdatedAt(LocalDateTime.now());
        userMapper.updateById(users);
    }
}
